import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:location_test/app/core/routes/app_routes.dart';
import 'package:location_test/app/data/datasources/remote/mqtt_service.dart';
import 'package:location_test/app/domain/models/ble_beacon.dart';
import 'package:location_test/app/presentation/controllers/home_controller.dart';
import 'package:location_test/app/presentation/widgets/info_card.dart';
import 'package:location_test/app/presentation/widgets/mqtt_config_dialog.dart';

class HomeView extends GetView<HomeController> {
  const HomeView({super.key});

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);

    return Scaffold(
      appBar: AppBar(
        title: const Text('GPS MQTT'),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.history),
            tooltip: '上传历史',
            onPressed: () => Get.toNamed(Routes.UPLOAD_HISTORY),
          ),
          IconButton(
            icon: const Icon(Icons.settings),
            tooltip: 'MQTT 配置',
            onPressed: () => _showMqttConfigDialog(context),
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Obx(() => _buildMqttControlCard(context, theme)),
            const SizedBox(height: 16),
            Obx(() => _buildSendingControlCard(theme)),
            const SizedBox(height: 16),
            Obx(() => _buildBleControlCard(theme)),
            const SizedBox(height: 16),
            InfoCard(
              title: 'WGS-84 坐标',
              icon: Icons.location_on,
              iconColor: Colors.green,
              right: TextButton(
                onPressed: () => Get.toNamed(Routes.HISTORY),
                child: const Text('定位记录'),
              ),
              child: Obx(_buildLocationContent),
            ),
            const SizedBox(height: 16),
            InfoCard(
              title: 'GPS 状态',
              icon: Icons.satellite_alt,
              iconColor: Colors.amber,
              right: TextButton(
                onPressed: () => Get.toNamed(Routes.NMEA_LOG),
                child: const Text('查看日志'),
              ),
              child: Obx(_buildNmeaContent),
            ),
            const SizedBox(height: 16),
            InfoCard(
              title: '设备状态',
              icon: Icons.power,
              iconColor: Colors.cyan,
              child: Obx(_buildDeviceStatusContent),
            ),
            const SizedBox(height: 16),
            Obx(() => _buildStatusLog(theme)),
          ],
        ),
      ),
    );
  }

  Widget _buildMqttControlCard(BuildContext context, ThemeData theme) {
    Color statusColor = Colors.red;
    String statusText = '已断开';
    IconData statusIcon = Icons.cloud_off;

    switch (controller.mqttConnectionState.value) {
      case MqttConnectionState.connected:
        statusColor = Colors.green;
        statusText = '已连接';
        statusIcon = Icons.cloud_done;
        break;
      case MqttConnectionState.connecting:
        statusColor = Colors.orange;
        statusText = '连接中...';
        statusIcon = Icons.cloud_upload;
        break;
      case MqttConnectionState.disconnected:
        break;
    }

    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                Icon(statusIcon, color: statusColor, size: 28),
                const SizedBox(width: 12),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('MQTT 状态: $statusText', style: theme.textTheme.titleMedium),
                    Text(
                      controller.mqttBrokerAddress.isEmpty
                          ? '未配置'
                          : controller.mqttBrokerAddress.value,
                      style: theme.textTheme.bodySmall,
                    ),
                  ],
                ),
              ],
            ),
            ElevatedButton(
              onPressed: controller.mqttBrokerAddress.isEmpty
                  ? null
                  : () {
                      if (controller.mqttConnectionState.value == MqttConnectionState.disconnected) {
                        controller.connectMqtt();
                      } else {
                        controller.disconnectMqtt();
                      }
                    },
              child: Text(
                controller.mqttConnectionState.value == MqttConnectionState.disconnected ? '连接' : '断开',
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSendingControlCard(ThemeData theme) {
    return Card(
      elevation: 2,
      child: Column(
        children: [
          SwitchListTile(
            title: Text('定位数据发送', style: theme.textTheme.titleMedium),
            value: controller.isSendingData.value,
            onChanged: controller.toggleSendingData,
            secondary: Icon(
              controller.isSendingData.value ? Icons.pause_circle_filled : Icons.play_circle_filled,
              color: controller.isSendingData.value ? Colors.redAccent : Colors.green,
              size: 32,
            ),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Row(
              children: [
                const Text('上报间隔 (秒):'),
                Expanded(
                  child: Slider(
                    value: math.max(1, controller.sendInterval.value),
                    min: 1,
                    max: 60,
                    divisions: 59,
                    label: controller.sendInterval.value.round().toString(),
                    onChanged: controller.setSendInterval,
                  ),
                ),
                Text(controller.sendInterval.value.round().toString()),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBleControlCard(ThemeData theme) {
    final bool enabled = controller.isBleReceiving.value;
    final List<BleBeacon> bleSnapshot = controller.bleReadings.toList();

    return Card(
      elevation: 2,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          SwitchListTile(
            title: Text('蓝牙广播接收', style: theme.textTheme.titleMedium),
            value: enabled,
            onChanged: (value) {
              controller.toggleBleReceiving(value);
            },
            secondary: Icon(
              enabled ? Icons.bluetooth_searching : Icons.bluetooth_disabled,
              color: enabled ? Colors.blueAccent : Colors.grey,
              size: 32,
            ),
          ),
          if (enabled)
            Padding(
              padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
              child: _buildBleReadingsContent(bleSnapshot, theme),
            ),
        ],
      ),
    );
  }

  Widget _buildBleReadingsContent(List<BleBeacon> readings, ThemeData theme) {
    if (readings.isEmpty) {
      return const Text('当前暂无广播数据');
    }

    return Column(
      children: readings.take(5).map<Widget>((dynamic item) {
        final timestamp = _formatTime(item.timestamp);
        return ListTile(
          dense: true,
          contentPadding: EdgeInsets.zero,
          leading: const Icon(Icons.bluetooth_audio, size: 20, color: Colors.blueAccent),
          title: Text('Major: ${item.major}  Minor: ${item.minor}'),
          subtitle: Text('RSSI: ${item.rssi}'),
          trailing: Text(
            timestamp,
            style: theme.textTheme.bodySmall,
          ),
        );
      }).toList(),
    );
  }

  Widget _buildLocationContent() {
    final Position? position = controller.currentPosition.value;
    if (position == null && !controller.isSendingData.value) {
      return const Center(child: Text('请开启数据发送'));
    }
    if (position == null) {
      return const Center(child: Text('正在等待定位数据...'));
    }
    return Column(
      children: [
        ListTile(title: const Text('经度:'), trailing: Text(position.longitude.toStringAsFixed(6))),
        ListTile(title: const Text('纬度:'), trailing: Text(position.latitude.toStringAsFixed(6))),
        ListTile(title: const Text('海拔:'), trailing: Text('${position.altitude.toStringAsFixed(2)} m')),
        ListTile(title: const Text('速度:'), trailing: Text('${(position.speed * 3.6).toStringAsFixed(2)} km/h')),
        ListTile(title: const Text('精度:'), trailing: Text('${position.accuracy.toStringAsFixed(2)} m')),
      ],
    );
  }

  Widget _buildNmeaContent() {
    return Column(
      children: [
        ListTile(
          title: const Text('使用中的卫星数:'),
          trailing: Text(controller.satellitesInUse.value?.toString() ?? 'N/A'),
        ),
        ListTile(
          title: const Text('水平精度 (HDOP):'),
          trailing: Text(controller.hdop.value?.toStringAsFixed(2) ?? 'N/A'),
        ),
        ListTile(
          title: const Text('垂直精度 (VDOP):'),
          trailing: Text(controller.vdop.value?.toStringAsFixed(2) ?? 'N/A'),
        ),
      ],
    );
  }

  Widget _buildDeviceStatusContent() {
    final int level = controller.batteryLevel.value;
    return ListTile(
      leading: const Icon(Icons.battery_std),
      title: const Text('手机电量'),
      trailing: Text(level < 0 ? '获取中...' : '$level %'),
    );
  }

  Widget _buildStatusLog(ThemeData theme) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Text(
        '日志: ${controller.lastMessage.value}',
        style: theme.textTheme.bodySmall?.copyWith(fontStyle: FontStyle.italic),
        textAlign: TextAlign.center,
      ),
    );
  }

  void _showMqttConfigDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (_) {
        return MqttConfigDialog(
          initialBroker: controller.mqttBrokerAddress.value,
          onSave: controller.updateMqttBroker,
        );
      },
    );
  }

  String _formatTime(DateTime time) {
    final DateTime local = time.toLocal();
    final String hour = local.hour.toString().padLeft(2, '0');
    final String minute = local.minute.toString().padLeft(2, '0');
    final String second = local.second.toString().padLeft(2, '0');
    return '$hour:$minute:$second';
  }
}
